package com.wfk.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.image.common.RestUploadFileInfo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import redis.clients.jedis.Jedis;

public class FunctionUtils {

	/**
	 * 获取订单号
	 * 
	 * @param a 
	 *            
	 * @param b
	 * 
	 * @return
	 */
	public static final String getOrderCode(int a, int b) {
		String time;
		java.util.Calendar cal = new java.util.GregorianCalendar();
		int random = (int) (Math.random() * 900) + 100;
		time = "" + a + b + cal.get(Calendar.HOUR) + String.valueOf(random).charAt(0) + cal.get(Calendar.MINUTE)
				+ String.valueOf(random).charAt(1) + cal.get(Calendar.SECOND) + String.valueOf(random).charAt(2)
				+ cal.get(Calendar.MILLISECOND);
		return time;
	}

	/**
	 * 取得真实ip
	 * @param request
	 * @return
	 */
	public static String getRemoteRealAddr(HttpServletRequest request) {
		String ip = null;
		//X-Forwarded-For：Squid 服务代理
		String ipAddresses = request.getHeader("X-Forwarded-For");
		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//Proxy-Client-IP：apache 服务代理
			ipAddresses = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//WL-Proxy-Client-IP：weblogic 服务代理
			ipAddresses = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//HTTP_CLIENT_IP：有些代理服务器
			ipAddresses = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//X-Real-IP：nginx服务代理
			ipAddresses = request.getHeader("X-Real-IP");
		}

		//有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
		if (ipAddresses != null && ipAddresses.length() != 0) {
			ip = ipAddresses.split(",")[0];
		}

		//还是不能获取到，最后再通过request.getRemoteAddr();获取
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			ip = request.getRemoteAddr();
		}
		return ip ;
	}

	/**
	 * 手机号码隐藏显示
	 * @param phone
	 * @return
	 */
	public static String replay(String phone) {
		String str = phone;
		if (phone.length() > 3) {
			str = phone.substring(0, 3);
			str += "****";
		}
		if (phone.length() > 7) {
			str += phone.substring(7);
		}
		return str;
	}

	/**
	 * 字符串编码转换的实现方法
	 * 
	 * @param str
	 *            待转换的字符串
	 * @param newCharset
	 *            目标编码
	 */
	public String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			// 用默认字符编码解码字符串。与系统相关，中文windows默认为GB2312
			byte[] bs = str.getBytes();
			return new String(bs, newCharset); // 用新的字符编码生成字符串
		}
		return null;
	}

	/**
	 * BigDecimal 加减乘除
	 */
	/**
	 * 加
	 * 
	 * @param d1
	 *            加数
	 * @param d2
	 *            被加数
	 * @param index
	 *            保留位数
	 * @return 四舍五入 保留两位小数
	 */
	public static BigDecimal add(BigDecimal a1, BigDecimal a2, int index) {
		if(a1 == null){
			a1 = new BigDecimal(0) ;
		}
		if(a2 == null){
			a2 = new BigDecimal(0) ;
		}
		return a1.add(a2).setScale(index, BigDecimal.ROUND_HALF_UP);
	}

	/**
	 * 减
	 * 
	 * @param d1
	 *            减数
	 * @param d2
	 *            被减数
	 * @param index
	 *            保留位数
	 * @return 四舍五入 保留两位小数
	 */
	public static BigDecimal sub(BigDecimal a1, BigDecimal a2, int index) {
		if(a1 == null){
			a1 = new BigDecimal(0) ;
		}
		if(a2 == null){
			a2 = new BigDecimal(0) ;
		}
		return a1.subtract(a2).setScale(index, BigDecimal.ROUND_HALF_UP);
	}

	/**
	 * 乘
	 * 
	 * @param d1
	 *            乘数
	 * @param d2
	 *            被乘数
	 * @param index
	 *            保留位数
	 * @return 四舍五入 保留两位小数
	 */
	public static BigDecimal mul(BigDecimal a1, BigDecimal a2, int index) {
		return a1.multiply(a2).setScale(index, BigDecimal.ROUND_HALF_UP);
	}
	
	/**
	 * 多参数乘法 RoundUp模式
	 * @param params
	 * @param model
	 * @return
	 */
	public static BigDecimal mul(Integer model,int index,BigDecimal... params) {
		BigDecimal result = NumberUtil.mul(params);
		return result.setScale(index, model) ;
	}

	/**
	 * 除
	 * 
	 * @param d1被除数
	 * @param d2
	 *           除数
	 * @param index
	 *            保留位数
	 * @return 四舍五入 保留两位小数
	 */
	public static BigDecimal div(BigDecimal d1, BigDecimal d2, int index) {
		if(d1 == null){
			d1 = new BigDecimal(0) ;
		}
		if(d2 == null){
			d2 = new BigDecimal(0) ;
		}
		return d1.divide(d2, index, BigDecimal.ROUND_HALF_UP);
	}

	/**
	 * 判断两个int类型的是否相等
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static boolean isEquals(Integer a, Integer b) {
		if (a == null) {
			if (b.equals(a) || b == a) {
				return true;
			}
		} else {
			if (a.equals(b) || b == a) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 字符串数组转list int对象
	 * 
	 * @param arr
	 * @return
	 */
	public static List<Integer> getList(String[] arr) {
		List<Integer> list = new ArrayList<Integer>();
		for (String s : arr) {
			if (!StrUtil.isBlank(s)) {
				Integer a = Integer.parseInt(s);
				list.add(a);
			}
		}
		return list;
	}

	public static Integer[] getArr(String[] arr) {
		Integer[] intArr = new Integer[arr.length];
		for (int i = 0; i < arr.length; i++) {
			String s = arr[i];
			if (!StrUtil.isEmpty(s)) {
				Integer a = Integer.parseInt(s);
				intArr[i] = a;
			}
		}
		return intArr;
	}

	/**
	 * 字符串数组转list int对象
	 * 
	 * @param arr
	 * @return
	 */
	public static List<Integer> getList(Integer[] arr) {
		List<Integer> list = new ArrayList<Integer>();
		for (Integer s : arr) {
			if (s != null) {
				list.add(s);
			}
		}
		return list;
	}

	public static List<String> getStrList(Integer[] arr) {
		List<String> list = new ArrayList<String>();
		for (Integer s : arr) {
			if (s != null) {
				list.add(String.valueOf(s));
			}
		}
		return list;
	}

	public static List<String> getStrList(String[] arr) {
		List<String> list = new ArrayList<String>();
		for (String s : arr) {
			if (s != null) {
				list.add(s);
			}
		}
		return list;
	}

	/**
	 * 字符串数组转list int对象
	 * 
	 * @param arr
	 * @return
	 */
	public static Set<Integer> getSet(String[] arr) {
		Set<Integer> list = new HashSet<Integer>();
		for (String s : arr) {
			if (!StrUtil.isEmpty(s)) {
				Integer a = Integer.parseInt(s);
				list.add(a);
			}
		}
		return list;
	}

	public static Set<String> getStrSet(String[] arr) {
		Set<String> list = new HashSet<String>();
		for (String s : arr) {
			if (!StrUtil.isEmpty(s)) {
				list.add(s);
			}
		}
		return list;
	}

	public static String getString(List<String> list) {
		String str = "";
		for (String o : list) {
			str += o + ",";
		}
		if (str.length() > 0) {
			return str.substring(0, str.length() - 1);
		} else {
			return str;
		}
	}

	public static String getString(Integer[] list) {
		String str = "";
		for (Integer o : list) {
			str += o + ",";
		}
		if (str.length() > 0) {
			return str.substring(0, str.length() - 1);
		} else {
			return str;
		}
	}

	/**
	 * 字符串数组转list int对象 倒叙
	 * 
	 * @param arr
	 * @return
	 */
	public static List<Integer> getListDesc(String[] arr) {
		List<Integer> list = new ArrayList<Integer>();
		for (int i = arr.length - 1; i > -1; i--) {
			String s = arr[i];
			if (!StrUtil.isEmpty(s)) {
				Integer a = Integer.parseInt(s);
				list.add(a);
			}
		}
		return list;
	}

	/**
	 * 字符串数组转list int对象 倒叙 只去几位
	 * 
	 * @param arr
	 * @return
	 */
	public static List<Integer> getListDesc(String[] arr, Integer b) {
		List<Integer> list = new ArrayList<Integer>();
		Integer c = 0;
		for (int i = arr.length - 1; i > -1; i--) {
			if (c < b) {
				String s = arr[i];
				if (!StrUtil.isEmpty(s)) {
					Integer a = Integer.parseInt(s);
					list.add(a);
					c++;
				}
			}
		}
		return list;
	}

	/**
	 * 字节流返回
	 * @param response
	 * @param msg
	 */
	public static void getPrint(HttpServletResponse response, String msg) {
		try {
			PrintWriter out = response.getWriter();
			out.println(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 字符流返回
	 * @param response
	 * @param msg
	 */
	public static void getWriter(HttpServletResponse response, String msg) {
		try {
			response.getWriter().write(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//返回信息给客户端
    public static  void responseMessage(HttpServletResponse response, ResponseData responseData) {
        PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	response.setContentType("application/json; charset=utf-8");  
        String json = JSONObject.toJSONString(responseData);
        out.print(json);
        out.flush();
        out.close();
    }

	
	/**
	 * 百分比转小数
	 * @param percent
	 * @return
	 */
	public static BigDecimal percentToBigDecimal(String percent){
		NumberFormat nf= NumberFormat.getPercentInstance();
		double number = 0.00;
		try {
			number = nf.parse(percent).doubleValue();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		BigDecimal bigDecimal = BigDecimal.valueOf(number).setScale(3, BigDecimal.ROUND_HALF_UP);
		return bigDecimal;
	}
	
	/**
	 * 数字转为百分比
	 * @param num
	 * @return
	 * @throws ParseException
	 */
	public static String numToPercent(BigDecimal num){
		String percent = "";
		try {
			NumberFormat nf=NumberFormat.getPercentInstance();
			nf.setMaximumFractionDigits(1);
			percent = nf.format(num);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		percent = percent.substring(0, percent.length() - 1) ;
		return percent;
	}
	
	public static String numToPercent(String num){
		BigDecimal bDecimal = new BigDecimal(num);
		return numToPercent(bDecimal);
	}

	/**
	 * 临时上传文件用的  从某某网站爬的接口，正式环境请换成自己集成的上传文件
	 * @param inputStream
	 * @return
	 */
	public static String tempUpload(InputStream inputStream,String fileName) {
		HttpRequest httpRequest = HttpUtil.createPost("http://thyrsi.com//upload.php");
		byte[] data = new byte[1 * 1024 * 1024 * 5] ; //上传文件大小不能超过5M
		try {
			inputStream.read(data) ;
		} catch (IOException e) {
			e.printStackTrace();
		}
		int temp = 0;
		try {
			temp = inputStream.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(temp != -1) {
			return "" ; //超过5M，不进行上传
		}
		httpRequest.form("uploadimg",data , fileName) ;
		HttpResponse response = httpRequest.execute();
		String body = response.body();
		Document doc = Jsoup.parse(body);
		Element element = doc.select("a[target='_blank']").get(0);
		String imagePath = element.attr("href") ;
		return imagePath ;
	}
	
	public static Jedis getJedis(RedisConnectionFactory connectionFactory) {
		Field jedisField = ReflectionUtils.findField(JedisConnection.class, "jedis");
        ReflectionUtils.makeAccessible(jedisField);
        System.out.println(connectionFactory.getConnection());
        Jedis jedis = (Jedis) ReflectionUtils.getField(jedisField, connectionFactory.getConnection());
        return jedis ; 
	}
	
	/**
	 * 将key值按照ascii码排序，并拼接成url参数
	 * @param map
	 * @return
	 */
	public static String sortParam(Map<String, String> map) {
		if(map==null){
			return null;
		}
		List<String> keyList = new ArrayList<String>(map.keySet());
		Collections.sort(keyList);
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<keyList.size();i++){
			String key = keyList.get(i);
			Object value = map.get(key);
			sb.append(key+"="+value+"&");
		}
		return sb.substring(0, sb.length()-1) ;
	}
	
	/**
	 * 取得商品标记码
	 * @return
	 */
	public static String getFlagcode(String str) {
		if(StrUtil.isBlank(str)) {
			return "" ; 
		}
		int index = str.indexOf("-");
		if(index == -1) {
			return str ; 
		}else {
			return str.substring(0, index) ;
		}
	}
	
	
	/**
	 * 获取UUID 32位的
	 * @return
	 */
	public static String generateUuid(){
		//32位的
		String uuid = UUID.randomUUID().toString();
		String[] strArray = uuid.split("\\s*[-]\\s*");
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<strArray.length;i++){
			sb.append(strArray[i]);
		}
		uuid = sb.toString();
		return uuid;
		
	}
	
	/**
	 * 根据多媒体文件对象上传文件转字符串
	 * @return
	 * @throws IOException 
	 */
	public static String multipartToString(MultipartFile file,String path) throws IOException {
		if(file == null) {
			return ""; 
		}
		if(StrUtil.isBlank(path)) {
			return "" ; 
		}
		RestUploadFileInfo upload = com.image.common.Service.uploadImage(file.getOriginalFilename(), file.getInputStream(), path);
		if(upload.isStatus()) {
			return "" ; 
		}
		String filePath = upload.getServiceName() + upload.getFilePath() + upload.getFileName() ;
		return filePath ; 
	}
	
	public static void main(String[] args) {
		int hour = DateUtil.hour(new Date(), true);
		if(hour<9||hour>13) {
			System.out.println("111");
		}
	}
}
